﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
using System.Xml;
using System.IO;
using System.Runtime.InteropServices;
namespace PlanningGIS.MetadataEdit
{
    public partial class FrmMetaData : Form
    {
        string[] strImportCol = new string[] { "图号", "图名", "比例尺分母", "产品类型名称", "产品生产日期","入库日期", "所在测区代号","测区代号", "产品所有权单位名称","产品生产单位名称",
                "产品生产单位测绘资质","图幅等高距","实测测绘员","实测检查员","实测日期","修测员", "修测检查员","修侧日期", "项目名称","产品名称","动态_竣工更新单位","动态_竣工更新日期","动态_竣工更新人员","动态_竣工更新备注"};
        private OleDbConnection mOleDbConnection;
        private string mFileName;

        //[DllImport("\\dll\\SoftDogSetup.dll")]
        //private static extern int InstDriver(int iFlag);
        // [DllImport("\\dll\\SoftDogSetup.dll")]
       // private static extern int GetDogDriverInfo();
        public FrmMetaData()
        {
            InitializeComponent();
            //int n = GetDogDriverInfo();
            //if (n == 0)
            //{
            //    int v = InstDriver(1);
            //}
        }
        private void Form1_Load(object sender, EventArgs e)
        {
           
            openFileDialog1.Filter = "Access文件(*.mdb)|*.mdb";
            openFileDialog1.FileName = "元数据文件";

            saveFileDialog1.Filter = "Access文件(*.mdb)|*.mdb";
            saveFileDialog1.FileName = "元数据文件";
            
            cmbDataType.Items.Add("DLG");
            cmbDataType.Items.Add("DEM");
            cmbDataType.Items.Add("DOM");
           
           

#if(市县基础地理信息系统)

             cmbDataType.Items.Add("DRG");
            cmbDataType.Items.Add("测区数据");

            cmbScale.Items.Add("500");
            cmbScale.Items.Add("1000");
            cmbScale.Items.Add("2000");
            cmbScale.Items.Add("5000");
            cmbScale.Items.Add("10000");
            cmbScale.SelectedIndex = 0;

            cmbTfSpec.SelectedIndex =1;
            cmbTfNameStyle.SelectedIndex = 0;

            cmbDataUnit.Items.Add("千米");
            cmbDataUnit.Items.Add("百米");
            cmbDataUnit.Items.Add("十米");
            cmbDataUnit.Items.Add("米");
            cmbDataUnit.SelectedIndex = 0;
#else
            cmbScale.Items.Add("5000");
            cmbScale.Items.Add("10000");
            cmbScale.Items.Add("50000");          
            cmbScale.SelectedIndex = 1;

            cmbTfSpec.Visible=false;
            cmbTfNameStyle.Visible = false;
             cmbDataUnit.Visible=false;
             lblTfSpec.Visible = false;
             lblTfNameStyle.Visible = false;
             lblDataUnit.Visible = false;
#endif
             cmbDataType.SelectedIndex = 0;
            cmbColumn.DropDownStyle = ComboBoxStyle.DropDownList;          
        }

        private void btnOpen_Click(object sender, EventArgs e)
        {
            openFileDialog1.Filter = "mdb文件(*.mdb)|*.mdb";
            openFileDialog1.Multiselect = false ;
            if (openFileDialog1.ShowDialog() != DialogResult.OK) return;
            Application.DoEvents();
            try
            {
                this.Cursor = Cursors.WaitCursor;
                if (mOleDbConnection != null && mOleDbConnection.State == ConnectionState.Open)
                {
                    Save();
                }
                string strFile = openFileDialog1.FileName;
                txtFile.Text = strFile;
                if (mOleDbConnection != null && mOleDbConnection.State == ConnectionState.Open)
                {
                    mOleDbConnection.Close();
                    dataGridView1.DataSource = null;
                }
                mOleDbConnection = new OleDbConnection();
                mOleDbConnection.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + strFile;
                mFileName = strFile;
                try
                {
                    mOleDbConnection.Open();
                }
                catch (System.Exception)
                {
                    MessageBox.Show("打开数据文件失败", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                cmbDataType_SelectedIndexChanged(null, null);
            }
            catch (System.Exception)
            {
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void Save()
        {
            if (mOleDbConnection == null || mOleDbConnection.State != ConnectionState.Open) return;
            DataView pDv = dataGridView1.DataSource as DataView;
            if (pDv == null) return;
           //this.dataGridView1.Columns[2].Frozen = false;
            foreach (DataGridViewColumn c in dataGridView1.Columns)
            {
                c.Frozen = false;
            }
            DataTable dt = pDv.Table;
            this.Cursor = Cursors.WaitCursor;
            try
            {
                DataTable pDt = dt.Copy();
                pDt.Rows.Clear();
                if (pDt != null)
                {
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        DataRow pRow = dt.Rows[i];
                        if (pRow.RowState == DataRowState.Unchanged || pRow.RowState == DataRowState.Modified || pRow.RowState == DataRowState.Added)
                        {
                            DataRow pRow2 = pDt.NewRow();
                            pRow2.ItemArray = pRow.ItemArray;
                            pDt.Rows.Add(pRow2);
                        }
                    }
                    Application.DoEvents();
                    string strSql = "delete from " + dt.TableName;
                    OleDbCommand pCmd = mOleDbConnection.CreateCommand();
                    pCmd.CommandText = strSql;
                  int count=   pCmd.ExecuteNonQuery();

                  strSql = " select * from " + dt.TableName;
                    pCmd.CommandText = strSql;
                    OleDbDataAdapter pAdapter = new OleDbDataAdapter(pCmd);
                    OleDbCommandBuilder pCmdBuilder = new OleDbCommandBuilder(pAdapter);
                     count = pAdapter.Update(pDt);
                    dataGridView1.DataSource = pDt;
                }
                this.dataGridView1.Columns[2].Frozen = true ;
            }
            catch (System.Exception ex)
            {
            }
            this.Cursor = Cursors.Default;
        }
       
        private void btnSave_Click(object sender, EventArgs e)
        {
            if (saveFileDialog1.ShowDialog() != DialogResult.OK) return;
            if (mOleDbConnection != null && mOleDbConnection.State == ConnectionState.Open)
            {
                Save();
            }
            if (mOleDbConnection != null && mOleDbConnection.State == ConnectionState.Open)
            {
                mOleDbConnection.Close();
                dataGridView1.DataSource = null;
            }
            if (System.IO.File.Exists(saveFileDialog1.FileName))
            {
                try
                {
                    System.IO.File.Delete(saveFileDialog1.FileName);
                }
                catch (System.Exception)
                {
                    MessageBox.Show("文件被占用，覆盖失败！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            }
            mFileName = saveFileDialog1.FileName;
            txtFile.Text = saveFileDialog1.FileName;
            System.Reflection.ManifestResourceInfo pRes = this.GetType().Assembly.GetManifestResourceInfo("MetadataEdit.元数据模板.mdb");
            System.IO.Stream pStrem = this.GetType().Assembly.GetManifestResourceStream("MetadataEdit.元数据模板.mdb");
            string[] strs = this.GetType().Assembly.GetManifestResourceNames();
          
            System.IO.FileStream fs = new System.IO.FileStream(mFileName, System.IO.FileMode.CreateNew);
            byte[] bts = new byte[pStrem.Length];
            pStrem.Read(bts, 0, bts.Length);
            fs.Write(bts, 0, bts.Length);
            fs.Close();        
            mOleDbConnection = new OleDbConnection();
            mOleDbConnection.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + mFileName;
            try
            {
                mOleDbConnection.Open();
            }
            catch (System.Exception)
            {
                MessageBox.Show("打开数据文件失败", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            cmbDataType_SelectedIndexChanged(null, null);          
        }
 
        private void dataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
           
        }

        private void btnUpdateColumn_Click(object sender, EventArgs e)
        {
            if (cmbColumn.Text == "") return;
            if (dataGridView1.Columns[cmbColumn.Text] == null) return;
            if (dataGridView1.Columns[cmbColumn.Text].ReadOnly) return;
            DataView dv = dataGridView1.DataSource as DataView;
            DataTable dt = dv.Table;
            if (dt == null) return;
            string strValue = txtColValue.Text.Trim();
            Type t = dt.Columns[cmbColumn.Text ].DataType;
            switch (t.Name)
            {
                case "Single":
                case "Double":
                case "Decimal":
                case "Int16":
                case "Int32":
                case "Int64":
                    {
                        double dbl;
                        if (!double.TryParse(strValue, out dbl))
                        {
                            MessageBox.Show("请输入数字！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);                           
                            return;
                        }
                        break;
                    }
                case "DateTime":
                    {
                        DateTime date;
                        if (!DateTime.TryParse(strValue, out date))
                        {
                            MessageBox.Show("请输入日期！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);                         
                            return;
                        }
                        break;
                    }
                default:
                    {
                        break;
                    }
            }
            for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
                dataGridView1.Rows[i].Cells[cmbColumn.Text].Value= txtColValue.Text.Trim();
            }                    
        }

  
        private void btnClear_Click(object sender, EventArgs e)
        {
            if (dataGridView1.Rows.Count == 0) return;
            if (MessageBox.Show(this, "确实要清空吗?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) != DialogResult.Yes)
            {
                return;
            }
            try
            {
                DataView dv = dataGridView1.DataSource as DataView;
                if (dv != null)
                {                  
                    dv.Table.Rows.Clear();
                }
                else { this.dataGridView1.Rows.Clear(); }
            }
            catch (System.Exception)
            {
            }
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (dataGridView1.SelectedRows.Count == 0) return;
            if (MessageBox.Show(this, "确实要删除吗?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) != DialogResult.Yes)
            {
                return;
            }
            foreach (DataGridViewRow  pRow in dataGridView1.SelectedRows) 
            {
               if(pRow.IsNewRow==false )   
                dataGridView1.Rows.Remove(pRow); 
            }
        }

        private void btnExport_Click(object sender, EventArgs e)
        {
            if (dataGridView1.Rows.Count == 0) return;
            FolderBrowserDialog fbd = new FolderBrowserDialog();
            fbd.ShowNewFolderButton = true;
            
            fbd.Description = "选择导出路径";
            if (fbd.ShowDialog() != DialogResult.OK)
            {
                return;
            }
            int count = 0;

            int errorDateCount = 0;
            int errCoordinateCount = 0;
            int errImpDateCount = 0;
            int errCQ = 0;
            if (cmbDataType.Text != "测区数据")
            {
                if (dataGridView1.Columns["产品生产日期"] != null)
                {
                    foreach (DataGridViewRow pRow in dataGridView1.Rows)
                    {
                        if (pRow.Cells["图号"].Value == null || pRow.Cells["图号"].Value.ToString().Trim() == "") continue;

                        if (pRow.Cells["产品生产日期"].Value == null || pRow.Cells["产品生产日期"].Value == DBNull.Value)
                        {
                            errorDateCount++;
                        }
                        #if!(市县基础地理信息系统)
                        //if (pRow.Cells["入库日期"].Value == null || pRow.Cells["入库日期"].Value == DBNull.Value)
                        //{
                        //    errImpDateCount++;
                        //}
                        //if (pRow.Cells["所在测区代号"].Value == null || pRow.Cells["所在测区代号"].Value == DBNull.Value)
                        //{
                        //    errCQ++;
                        //}
                        #endif

                        if (dataGridView1.Columns.Contains("西南图廓角点X坐标") && pRow.Cells["西南图廓角点X坐标"].Value == DBNull.Value)
                        {
                            errCoordinateCount++;
                        }
                        else if (dataGridView1.Columns.Contains("西南图廓角点Y坐标") && pRow.Cells["西南图廓角点Y坐标"].Value == DBNull.Value)
                        {
                            errCoordinateCount++;
                        }
                        else if (dataGridView1.Columns.Contains("东北图廓角点X坐标") && pRow.Cells["东北图廓角点X坐标"].Value == DBNull.Value)
                        {
                            errCoordinateCount++;
                        }
                        else if (dataGridView1.Columns.Contains("东北图廓角点Y坐标") && pRow.Cells["东北图廓角点Y坐标"].Value == DBNull.Value)
                        {
                            errCoordinateCount++;
                        }

                        else if (dataGridView1.Columns.Contains("图廓角点最小X坐标") && pRow.Cells["图廓角点最小X坐标"].Value == DBNull.Value)
                        {
                            errCoordinateCount++;
                        }
                        else if (dataGridView1.Columns.Contains("图廓角点最小Y坐标") && pRow.Cells["图廓角点最小Y坐标"].Value == DBNull.Value)
                        {
                            errCoordinateCount++;
                        }
                        else if (dataGridView1.Columns.Contains("图廓角点最大X坐标") && pRow.Cells["图廓角点最大X坐标"].Value == DBNull.Value)
                        {
                            errCoordinateCount++;
                        }
                        else if (dataGridView1.Columns.Contains("图廓角点最大Y坐标") && pRow.Cells["图廓角点最大Y坐标"].Value == DBNull.Value)
                        {
                            errCoordinateCount++;
                        }

                    }
                }
                if (errorDateCount > 0)
                {
                    MessageBox.Show("共有" + errorDateCount + "条记录未输入产品生产日期,导出失败！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                if (errImpDateCount > 0)
                {
                    MessageBox.Show("共有" + errImpDateCount + "条记录未输入入库日期,导出失败！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                if (errCQ > 0)
                {
                    MessageBox.Show("共有" + errCQ + "条记录未输入所在测区代号,导出失败！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                if (errCoordinateCount > 0)
                {
                    MessageBox.Show("共有" + errCoordinateCount + "条记录产品图廓角点坐标输入错误或未输入,导出失败！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
            }         
            foreach (DataGridViewRow pRow in dataGridView1.Rows)
            {
                if (Row2Xml(fbd.SelectedPath, pRow))
                {
                    count++;
                }
            }
            MessageBox.Show("导出完毕，共导出"+count +"个元数据文件!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void btnExportSelected_Click(object sender, EventArgs e)
        {
            if (dataGridView1.SelectedRows.Count == 0) return;
            FolderBrowserDialog fbd = new FolderBrowserDialog();
            fbd.ShowNewFolderButton = true;

            fbd.Description = "选择导出路径";
            if (fbd.ShowDialog() != DialogResult.OK)
            {
                return;
            }
            int count = 0;

            int errorDateCount = 0;
            int errCoordinateCount = 0;
            int errImpDateCount = 0;
            int errCQ = 0;
            if (cmbDataType.Text != "测区数据")
            {
                if (dataGridView1.Columns["产品生产日期"] != null)
                {
                    foreach (DataGridViewRow pRow in dataGridView1.SelectedRows)
                    {
                        if (pRow.Cells["图号"].Value == null || pRow.Cells["图号"].Value.ToString().Trim() == "") continue;

                        if (pRow.Cells["产品生产日期"].Value == null || pRow.Cells["产品生产日期"].Value == DBNull.Value)
                        {
                            errorDateCount++;
                        }
#if!(市县基础地理信息系统)
                        //if (pRow.Cells["入库日期"].Value == null || pRow.Cells["入库日期"].Value == DBNull.Value)
                        //{
                        //    errImpDateCount++;
                        //}
                        //if (pRow.Cells["所在测区代号"].Value == null || pRow.Cells["所在测区代号"].Value == DBNull.Value)
                        //{
                        //    errCQ++;
                        //}
#endif

                        if (dataGridView1.Columns.Contains("西南图廓角点X坐标") && pRow.Cells["西南图廓角点X坐标"].Value == DBNull.Value)
                        {
                            errCoordinateCount++;
                        }
                        else if (dataGridView1.Columns.Contains("西南图廓角点Y坐标") && pRow.Cells["西南图廓角点Y坐标"].Value == DBNull.Value)
                        {
                            errCoordinateCount++;
                        }
                        else if (dataGridView1.Columns.Contains("东北图廓角点X坐标") && pRow.Cells["东北图廓角点X坐标"].Value == DBNull.Value)
                        {
                            errCoordinateCount++;
                        }
                        else if (dataGridView1.Columns.Contains("东北图廓角点Y坐标") && pRow.Cells["东北图廓角点Y坐标"].Value == DBNull.Value)
                        {
                            errCoordinateCount++;
                        }

                        else if (dataGridView1.Columns.Contains("图廓角点最小X坐标") && pRow.Cells["图廓角点最小X坐标"].Value == DBNull.Value)
                        {
                            errCoordinateCount++;
                        }
                        else if (dataGridView1.Columns.Contains("图廓角点最小Y坐标") && pRow.Cells["图廓角点最小Y坐标"].Value == DBNull.Value)
                        {
                            errCoordinateCount++;
                        }
                        else if (dataGridView1.Columns.Contains("图廓角点最大X坐标") && pRow.Cells["图廓角点最大X坐标"].Value == DBNull.Value)
                        {
                            errCoordinateCount++;
                        }
                        else if (dataGridView1.Columns.Contains("图廓角点最大Y坐标") && pRow.Cells["图廓角点最大Y坐标"].Value == DBNull.Value)
                        {
                            errCoordinateCount++;
                        }

                    }
                }
                if (errorDateCount > 0)
                {
                    MessageBox.Show("共有" + errorDateCount + "条记录未输入产品生产日期,导出失败！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                if (errImpDateCount > 0)
                {
                    MessageBox.Show("共有" + errImpDateCount + "条记录未输入入库日期,导出失败！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                if (errCQ > 0)
                {
                    MessageBox.Show("共有" + errCQ + "条记录未输入所在测区代号,导出失败！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                if (errCoordinateCount > 0)
                {
                    MessageBox.Show("共有" + errCoordinateCount + "条记录产品图廓角点坐标输入错误或未输入,导出失败！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
            }
            foreach (DataGridViewRow pRow in dataGridView1.Rows)
            {
                if (Row2Xml(fbd.SelectedPath, pRow))
                {
                    count++;
                }
            }
            MessageBox.Show("导出完毕，共导出" + count + "个元数据文件!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        private bool Row2Xml(string strPath, DataGridViewRow pRow)
        {
            try
            {
                string strFile="";
                string strTfbh ="";
                if (cmbDataType.Text != "测区数据")
                {
                    if (pRow.Cells["图号"].Value == null || pRow.Cells["图号"].Value == DBNull.Value || pRow.Cells["图号"].Value.ToString().Trim() == "")
                        return false;
                    strTfbh = pRow.Cells["图号"].Value.ToString().Trim();
                    strTfbh= ProcessMapNo(strTfbh);
                }
                else
                {
                    if (pRow.Cells["测区代号"].Value == null || pRow.Cells["测区代号"].Value == DBNull.Value || pRow.Cells["测区代号"].Value.ToString().Trim() == "")
                        return false;
                    strTfbh = pRow.Cells["测区代号"].Value.ToString().Trim(); 
                }                                        
                if (pRow.Tag == null)
                {
                    strFile = strTfbh;
                }
                else
                {
                    strFile = pRow.Tag.ToString();
                    strFile = ProcessMapNo(strFile);
                }
                XmlDocument pXmlDoc = new XmlDocument();
                XmlElement pElemItems = pXmlDoc.CreateElement("MetaDataItems");
                pXmlDoc.AppendChild(pElemItems);
                foreach (DataGridViewColumn pColumn in dataGridView1.Columns)
                {
                    if(pColumn.Name=="ID")continue;
                    XmlElement pElemItem = pXmlDoc.CreateElement(pColumn.Name);
                    if (pRow.Cells[pColumn.Name].Value is DateTime)
                    {
                        pElemItem.InnerText = ((DateTime)pRow.Cells[pColumn.Name].Value).ToShortDateString();
                        pElemItems.AppendChild(pElemItem);
                    }
                    else
                    {
                        pElemItem.InnerText = pRow.Cells[pColumn.Name].Value == null ? "" : pRow.Cells[pColumn.Name].Value.ToString();
#if 市县基础地理信息系统
                        if (pColumn.Name == "图号" || pColumn.Name == "图幅接合表西北图幅名称"
                            || pColumn.Name == "图幅接合表北图幅名称"
                            || pColumn.Name == "图幅接合表东北图幅名称"
                            || pColumn.Name == "图幅接合表西图幅名称"
                            || pColumn.Name == "图幅接合表东图幅名称"
                            || pColumn.Name == "图幅接合表西南图幅名称"
                            || pColumn.Name == "图幅接合表南图幅名称"
                            || pColumn.Name == "图幅接合表东南图幅名称")
                        {
                            pElemItem.InnerText = ProcessMapNo(pElemItem.InnerText);
                        }
#endif
                        pElemItems.AppendChild(pElemItem);
                    }
                }
                if (System.IO.File.Exists(strPath + "\\" + strFile + ".xml"))
                {
                    System.IO.File.Delete(strPath + "\\" + strFile + ".xml");
                }
                pXmlDoc.Save(strPath + "\\" + strFile + ".xml");
                return true;
            }
            catch (System.Exception)
            {
                return false;
            }
        }

        private DataRow Xml2Row(string strFile)
        {
            DataRow pRow = null;
            try
            {
                XmlDocument pXmlDoc = new XmlDocument();
                pXmlDoc.Load(strFile);
                XmlNode  pNodeMetaData = pXmlDoc.SelectSingleNode("MetaDataItems");
                if (pNodeMetaData == null)
                {
                    pNodeMetaData = pXmlDoc.SelectSingleNode("MeataDataItems");
                    if(pNodeMetaData==null )
                    return null;
                }
                DataView pDv = dataGridView1.DataSource as DataView;
                 pRow = pDv.Table.NewRow();
                 foreach (XmlNode pNode in pNodeMetaData.ChildNodes)
                 {
                     if (pNode is XmlElement)
                     {
                         DataColumn pCol = pRow.Table.Columns[pNode.Name];
                         if (pCol == null) continue;

                         if (pCol.DataType == typeof(float) || pCol.DataType == typeof(double))
                         {
                             double dbl;
                             if (double.TryParse(pNode.InnerText, out dbl)) pRow[pNode.Name] = dbl;
                         }
                         else if (pCol.DataType == typeof(short) || pCol.DataType == typeof(int) || pCol.DataType == typeof(long))
                         {
                             int ival;
                             if (int.TryParse(pNode.InnerText, out ival)) pRow[pNode.Name] = ival;
                         }
                         else if (pCol.DataType == typeof(DateTime))
                         {
                             DateTime dt;
                             if (DateTime.TryParse(pNode.InnerText, out dt)) pRow[pNode.Name] = dt;
                         }
                         else
                         {
                             if(pNode.InnerText!=null )
                             pRow[pNode.Name] = pNode.InnerText.ToUpper();
                         }

                     }
                 }
                 if (cmbDataType.Text != "测区数据")
                 {
                     if (pRow["图号"] != null && pRow["图号"] != DBNull.Value && pRow["图号"].ToString().Trim() != "")
                     {
                         pDv.Table.Rows.Add(pRow);
                     }
                 }
                 else
                 {
                     if (pRow["测区代号"] != null && pRow["测区代号"] != DBNull.Value && pRow["测区代号"].ToString().Trim() != "")
                     {
                         pDv.Table.Rows.Add(pRow);
                     }
                 }               
            }
            catch (System.Exception)
            {
                return null ;
            }
            return pRow;
        }
        private void cmbDataType_SelectedIndexChanged(object sender, EventArgs e)
        {
            cmbScale.Enabled = cmbDataType.Text != "测区数据";
            cmbDataUnit.Enabled = cmbDataType.Text != "测区数据";
            cmbTfNameStyle.Enabled = cmbDataType.Text != "测区数据";
            cmbTfSpec.Enabled = cmbDataType.Text != "测区数据";
            cmbDataUnit.Enabled = cmbDataType.Text != "测区数据";
            btnAutoUpdate.Enabled = cmbDataType.Text != "测区数据";         
            if (cmbDataType.Text == "测区数据")
            {               
                BindCqTable();
            }
            else
            {
                BindTable();
            }            
        }

        private void BindTable()
        {
            if (mOleDbConnection == null || mOleDbConnection.State != ConnectionState.Open) return;
            Save();
            string strMetaDataTable;
             #if 市县基础地理信息系统
            switch (cmbDataType.Text)
            {
                case "DLG":
                    strMetaDataTable = "md_500_dlg_tf";
                    break;
                case "DEM":
                    strMetaDataTable = "md_500_dem_tf";
                    break;
                case "DOM":
                    strMetaDataTable = "md_500_dom_tf";
                    break;
                case "DRG":
                    strMetaDataTable = "md_500_drg_tf";
                    break;
                default:
                    {
                        return;
                    }
            }
#else
            switch (cmbDataType.Text)
            {
                case "DLG":
                    strMetaDataTable = "md_dlg";
                    break;
                case "DEM":
                    strMetaDataTable = "md_dem";
                    break;
                case "DOM":
                    strMetaDataTable = "md_dom";
                    break;            
                default:
                    {
                        return;
                    }
            }
#endif
            try
            {
                string strSql = " select * from " + strMetaDataTable;
                OleDbCommand pCmd = mOleDbConnection.CreateCommand();
                pCmd.CommandText = strSql;
                OleDbDataAdapter pAdapter = new OleDbDataAdapter(pCmd);
                DataSet pDst = new DataSet();
                pAdapter.Fill(pDst);
                DataTable pDt = pDst.Tables[0];
                pDt.TableName = strMetaDataTable;
                DataView pDv = pDt.DefaultView;

                pDv.AllowEdit = true;
                pDv.AllowNew = true;
                foreach (DataGridViewColumn c in dataGridView1.Columns)
                {
                    c.Frozen = false;
                }
                dataGridView1.DataSource = pDv;
                dataGridView1.Columns[2].Frozen = true;

                if (dataGridView1.Columns["ID"] != null)
                {
                    dataGridView1.Columns["ID"].Visible = false;
                }
                if (dataGridView1.Columns["序号"] != null)
                {
                    dataGridView1.Columns["序号"].Visible = false;
                }
                string[] strReadOnlyCol = new string[] {"ID","产品类型名称","西南图廓角点X坐标","西南图廓角点Y坐标",
                "西北图廓角点X坐标","西北图廓角点Y坐标","东北图廓角点X坐标","东北图廓角点Y坐标","东南图廓角点X坐标","东南图廓角点Y坐标"};

                foreach (string str in strReadOnlyCol)
                {
                    if (dataGridView1.Columns[str] != null)
                    {
                        dataGridView1.Columns[str].ReadOnly = true;
                         
                    }
                }
                List<string> pList = new List<string>();
                pList.AddRange(strReadOnlyCol);
                cmbColumn.Items.Clear();
                for (int i = 0; i < dataGridView1.Columns.Count; i++)
                {
                    if ((!pList.Contains(dataGridView1.Columns[i].Name)) & dataGridView1.Columns[i].Name != "图号")
                    {
                        cmbColumn.Items.Add(dataGridView1.Columns[i].Name);
                    }
                }
                cmbColumn.SelectedIndex = 0;

            
              
                List<string> importCols = strImportCol.ToList();
              
                foreach (DataGridViewColumn pColumn in dataGridView1.Columns)
                {
                    if (pColumn.Name != "图号")
                    {
                        pColumn.SortMode = DataGridViewColumnSortMode.NotSortable;
                    }

                    //added by sheng  同上
                    pColumn.Visible = importCols.Contains(pColumn.Name);

                
                }
                dataGridView1.Columns[2].Frozen = true;
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
        private void BindCqTable()
        {
            string strCqTable = "md_500_cq";
            if (mOleDbConnection == null || mOleDbConnection.State != ConnectionState.Open) return;
            Save();
            string strSql = " select * from " + strCqTable;
            OleDbCommand pCmd = mOleDbConnection.CreateCommand();
            pCmd.CommandText = strSql;
            OleDbDataAdapter pAdapter = new OleDbDataAdapter(pCmd);
            DataSet pDst = new DataSet();
            pAdapter.Fill(pDst);
            DataTable pDt = pDst.Tables[0];
            pDt.TableName = strCqTable;
            DataView pDv = pDt.DefaultView;
            pDv.AllowEdit = true;
            pDv.AllowNew = true;
            dataGridView1.DataSource = pDv;          
            cmbColumn.Items.Clear();
            for (int i = 0; i < dataGridView1.Columns.Count; i++)
            {
                if ( dataGridView1.Columns[i].Name != "ID" & dataGridView1.Columns[i].Name != "测区代号" & dataGridView1.Columns[i].Name != "测区名称")
                cmbColumn.Items.Add(dataGridView1.Columns[i].Name);
            }
            if(cmbColumn.Items.Count>0)
            cmbColumn.SelectedIndex = 0;
        }
       
        private void FrmMetaData_FormClosing(object sender, FormClosingEventArgs e)
        {
            //if (MessageBox.Show(this, "确定要退出吗?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) != DialogResult.Yes)
            //{
            //    e.Cancel = true;
            //    return;
            //}
            //else
            //{
                Save();
           // }
        }            
         private void btnGetThFromDwg_Click(object sender, EventArgs e)
         {
             if (dataGridView1.DataSource == null) return;
             if (cmbDataType.Text == "DLG" || cmbDataType.Text=="测区数据")
             {
                 openFileDialog2.Filter = "DLG文件(*.dwg;*.dgn)|*.dwg;*.dgn";
             }
             else if (cmbDataType.Text == "DOM")
             {
                 openFileDialog2.Filter = "DOM文件(*.tif,*.img)|*.tif;*.img";
             }
             else if (cmbDataType.Text == "DEM")
             {
                 openFileDialog2.Filter = "DEM文件(*.img,*.tif)|*.dem;*.tif;*.img";
             }
             else
             {
                 openFileDialog2.Filter = "DRG文件(*.jpg,*.jpeg,*.bmp)|*.jpg;*.jpeg;*.bmp";
             }           
             openFileDialog2.Multiselect = true;
             if (openFileDialog2.ShowDialog() != DialogResult.OK) return;
             this.Cursor = Cursors.WaitCursor;
             Application.DoEvents();
             try
             {
                 string[] strFiles = openFileDialog2.FileNames;
                
                 DataView pDv = dataGridView1.DataSource as DataView;
        #if 市县基础地理信息系统
                  float dblLeft, dblRight;
                 double dblUnit = 1;
                 switch (cmbDataUnit.Text)
                 {
                     case "千米":
                         {
                             dblUnit = 1;
                             break;
                         }
                     case "百米":
                         {
                             dblUnit = 0.1;
                             break;
                         }
                     case "十米":
                         {
                             dblUnit = 0.01;
                             break;
                         }
                     case "米":
                         {
                             dblUnit = 0.001;
                             break;
                         }
                     default:
                         {
                             break;
                         }
                 }
        #else
                  double dblLong, dblLat;
                char rowNoMillion;
                string strColNoMillion, strRowNo, strColNo;
        #endif
               
                 int count = pDv.Table.Rows.Count;
                 int index = 0;                
                 foreach (string strFile in strFiles)
                 {
                     string str = System.IO.Path.GetFileNameWithoutExtension(strFile);
                     if(cmbDataType.Text !="测区数据")
                     {
                          string strTFBH_new="";
                         #if 市县基础地理信息系统
                          if (MapNoUtility.CheckTfbh500(str, out dblLeft, out dblRight))
                          {
                              switch (cmbScale.Text)
                              {
                                  case "500":

                                      
                                      strTFBH_new = (dblLeft * dblUnit).ToString("F2") + "-" + (dblRight * dblUnit).ToString("F2");
                                      break;
                                  case "1000":
                                     
                                      strTFBH_new = (dblLeft * dblUnit).ToString("F1") + "-" + (dblRight * dblUnit).ToString("F1");
                                      break;
                                  case "2000":
                                      strTFBH_new = (dblLeft * dblUnit).ToString("F0") + "-" + (dblRight * dblUnit).ToString("F0");
                                      break;
                                  case "5000":
                                     
                                      strTFBH_new = (dblLeft * dblUnit).ToString("F1") + "-" + (dblRight * dblUnit).ToString("F1");
                                      break;
                                  case "10000":
                                      strTFBH_new = (dblLeft * dblUnit).ToString("F0") + "-" + (dblRight * dblUnit).ToString("F0");
                                      break;
                                  default:
                                      strTFBH_new = "";
                                      break;
                              }
                          }
                          strTFBH_new= ProcessMapNo(strTFBH_new);
                          #else
                          switch (cmbScale.Text)
                          {
                              case"5000":
                                  if (!MapNoUtility.CheckTfbh5000(str, out rowNoMillion, out strColNoMillion, out strRowNo, out strColNo, out dblLong, out dblLat)) continue;
                                  strTFBH_new = str.ToUpper();
                                  break;
                              case "10000":
                                  if (!MapNoUtility.CheckTfbh10000(str, out rowNoMillion, out strColNoMillion, out strRowNo, out strColNo, out dblLong, out dblLat)) continue;
                                  strTFBH_new = str.ToUpper();
                                  break;
                              case "50000":
                                  if (!MapNoUtility.CheckTfbh50000(str, out rowNoMillion, out strColNoMillion, out strRowNo, out strColNo, out dblLong, out dblLat)) continue;
                                  strTFBH_new = str.ToUpper();
                                  break;
                               default:
                                    break;
                          }
                          #endif
                             if (strTFBH_new != "")
                             {
                                 DataRow pRow = pDv.Table.NewRow();
                                 pRow["图号"] = strTFBH_new;
                                 pRow["比例尺分母"] = cmbScale.Text;
                                 pDv.Table.Rows.Add(pRow);
                                 index++;
                                 dataGridView1.Rows[count + index - 1].Tag = str;
                             }
                         }                                             
                     else
                     {
                         DataRow pRow = pDv.Table.NewRow();
                         pRow["测区代号"] = str;
                         pRow["测区名称"] = str;
                         pDv.Table.Rows.Add(pRow);
                         index++;
                         dataGridView1.Rows[count + index - 1].Tag = str;
                     }
                 }
             }
             catch (System.Exception)
             {
             }
             finally
             {
                 this.Cursor = Cursors.Default;
             }
         }

         private void btnGetThFromTxt_Click(object sender, EventArgs e)
         {
             if (dataGridView1.DataSource == null) return;
             openFileDialog3.Filter = "txt文件(*.txt)|*.txt|dat文件(*.dat)|*.dat";
             openFileDialog3.Multiselect = false;
             if (openFileDialog3.ShowDialog() != DialogResult.OK) return;
             DataView pDv = dataGridView1.DataSource as DataView;
             StreamReader pStreamR = null;
             string str = "";
             float  dblLeft, dblRight;
             try
             {
                int   count = dataGridView1.Rows.Count;
                 pStreamR = new StreamReader(openFileDialog3.FileName, Encoding.Default);
                 str = pStreamR.ReadLine();
                 int index=0;
                 while (str != null )
                 {
                     if (cmbDataType.Text != "测区数据")
                     {
#if 市县基础地理信息系统
                         if (MapNoUtility.CheckTfbh500(str, out dblLeft, out dblRight))
                         {
                             DataRow pRow = pDv.Table.NewRow();
                             pRow["图号"] = str;
                             pRow["比例尺分母"] = cmbScale.Text;
                             pDv.Table.Rows.Add(pRow);
                             index++;
                             dataGridView1.Rows[count + index - 1].Tag = str;

                         }
#else
                         double dblLong, dblLat;
                         char rowNoMillion;
                         string strColNoMillion, strRowNo, strColNo;
                         string strTFBH_new = "";
                         switch( cmbScale.Text)
                         {
                             case "1:5000":
                                 if (!MapNoUtility.CheckTfbh5000(str, out rowNoMillion, out strColNoMillion, out strRowNo, out strColNo, out dblLong, out dblLat)) continue;
                                 strTFBH_new = str.ToUpper();
                                 break;
                             case "1:10000":
                                 if (!MapNoUtility.CheckTfbh10000(str, out rowNoMillion, out strColNoMillion, out strRowNo, out strColNo, out dblLong, out dblLat)) continue;
                                 strTFBH_new = str.ToUpper();
                                 break;
                             case "1:50000":
                                 if (!MapNoUtility.CheckTfbh50000(str, out rowNoMillion, out strColNoMillion, out strRowNo, out strColNo, out dblLong, out dblLat)) continue;
                                 strTFBH_new = str.ToUpper();
                                 break;
                             default:
                                 break;
                         }
                         if (strTFBH_new != "")
                         {
                             DataRow pRow = pDv.Table.NewRow();
                             pRow["图号"] = str;
                             pRow["比例尺分母"] = cmbScale.Text;
                             pDv.Table.Rows.Add(pRow);
                             index++;
                             dataGridView1.Rows[count + index - 1].Tag = str;
                         }
#endif
                     }
                     else
                     {
                         if (str.Trim() != "")
                         {
                             DataRow pRow = pDv.Table.NewRow();
                             pRow["测区代号"] = str.Trim();
                             pRow["测区名称"] = str.Trim();
                             pDv.Table.Rows.Add(pRow);
                             index++;
                             dataGridView1.Rows[count + index - 1].Tag = str.Trim();
                         }
                     }
                     str = pStreamR.ReadLine();
           
                 }
             }
             catch (System.Exception)
             {
             }
             finally
             {
                 pStreamR.Close();
                 pStreamR.Dispose();
             }
         }

       

         private void AutoCaculate()
         {
              
             if (dataGridView1.Rows.Count == 0) return;
             if (dataGridView1.Columns["图号"] == null) return;

             List<string> fields = new List<string>();
            #if  市县基础地理信息系统

             fields.Add("产品名称");
             fields.Add("密级");
             fields.Add("数据格式");
             fields.Add("图幅等高距");
             fields.Add("图式及图号");
             fields.Add("数据采集方法及仪器");


             fields.Add("图幅接合表西北图幅名称");
             fields.Add("图幅接合表北图幅名称");
             fields.Add("图幅接合表东北图幅名称");
             fields.Add("图幅接合表西图幅名称");
             fields.Add("图幅接合表东图幅名称");
             fields.Add("图幅接合表西南图幅名称");
             fields.Add("图幅接合表南图幅名称");
             fields.Add("图幅接合表东南图幅名称");

       

                
#else
             fields.Add("图幅接合表中西北图幅名称");
             fields.Add("图幅接合表中北图幅名称");
             fields.Add("图幅接合表中东北图幅名称");
             fields.Add("图幅接合表中西图幅名称");
             fields.Add("图幅接合表中东图幅名称");
             fields.Add("图幅接合表中西南图幅名称");
             fields.Add("图幅接合表中南图幅名称");
             fields.Add("图幅接合表中东南图幅名称");

             fields.Add("图廓角点最小X坐标");
             fields.Add("图廓角点最小Y坐标");
             fields.Add("图廓角点最大X坐标");
             fields.Add("图廓角点最大Y坐标");
            #endif
             fields.Add("西南图廓角点X坐标");
             fields.Add("西南图廓角点Y坐标");
             fields.Add("西北图廓角点X坐标");
             fields.Add("西北图廓角点Y坐标");
             fields.Add("东北图廓角点X坐标");
             fields.Add("东北图廓角点Y坐标");
             fields.Add("东南图廓角点X坐标");
             fields.Add("东南图廓角点Y坐标");
          
             FrmSelectField frm = new FrmSelectField();
             frm.Fields = fields;
             if (frm.ShowDialog() != DialogResult.OK) return;
             List<string> selectedFields = frm.SelectedFields;
             this.Cursor = Cursors.WaitCursor;
             try
             {
                 bool blnYX = cmbTfNameStyle.SelectedIndex == 0;
                 bool bln4X5 = cmbTfSpec.SelectedIndex == 1;
                 double dblHeight, dblWidth;
                 int precision = 2;               
                 DataTable dt = ((DataView)dataGridView1.DataSource).Table;

                 int index1 = -1;
                 if( selectedFields.Contains("西南图廓角点X坐标")) index1= dt.Columns.IndexOf("西南图廓角点X坐标");
                 int index2 = -1;
                 if (selectedFields.Contains("西南图廓角点Y坐标"))  index2 = dt.Columns.IndexOf("西南图廓角点Y坐标");
                 int index3 = -1;
                 if (selectedFields.Contains("西北图廓角点X坐标")) index3 = dt.Columns.IndexOf("西北图廓角点X坐标");
                 int index4 = -1;
                 if (selectedFields.Contains("西北图廓角点Y坐标")) index4= dt.Columns.IndexOf("西北图廓角点Y坐标");
                 int index5 = -1;
                 if (selectedFields.Contains("东北图廓角点X坐标")) index5 = dt.Columns.IndexOf("东北图廓角点X坐标");

                 int index6 = -1;
                 if(selectedFields.Contains("东北图廓角点Y坐标")) index6= dt.Columns.IndexOf("东北图廓角点Y坐标");

                 int index7 = -1;
                 if (selectedFields.Contains("东南图廓角点X坐标")) index7 = dt.Columns.IndexOf("东南图廓角点X坐标");
                 int index8 = -1;
                 if (selectedFields.Contains("东南图廓角点Y坐标")) index8 = dt.Columns.IndexOf("东南图廓角点Y坐标");

                   #if  市县基础地理信息系统
                          int index9 = -1;
                 if (selectedFields.Contains("图幅接合表西北图幅名称")) index9 = dt.Columns.IndexOf("图幅接合表西北图幅名称");
                 int index10 = -1;
                 if (selectedFields.Contains("图幅接合表北图幅名称")) index10 = dt.Columns.IndexOf("图幅接合表北图幅名称");
                 int index11 = -1;
                 if (selectedFields.Contains("图幅接合表东北图幅名称")) index11 = dt.Columns.IndexOf("图幅接合表东北图幅名称");
                 int index12 = -1;
                 if (selectedFields.Contains("图幅接合表西图幅名称")) index12 = dt.Columns.IndexOf("图幅接合表西图幅名称");
                 int index13 = -1;
                 if (selectedFields.Contains("图幅接合表东图幅名称")) index13 = dt.Columns.IndexOf("图幅接合表东图幅名称");
                 int index14 = -1;
                 if (selectedFields.Contains("图幅接合表西南图幅名称")) index14 = dt.Columns.IndexOf("图幅接合表西南图幅名称");
                 int index15 = -1;
                 if (selectedFields.Contains("图幅接合表南图幅名称")) index15 = dt.Columns.IndexOf("图幅接合表南图幅名称");
                 int index16 = -1;
                 if (selectedFields.Contains("图幅接合表东南图幅名称")) index16 = dt.Columns.IndexOf("图幅接合表东南图幅名称");

                 int index17 = -1;
                 if (selectedFields.Contains("产品名称")) index17 = dt.Columns.IndexOf("产品名称");
                 int index18 = -1;
                 if (selectedFields.Contains("密级")) index18 = dt.Columns.IndexOf("密级");
                 int index19 = -1;
                 if (selectedFields.Contains("数据格式")) index19 = dt.Columns.IndexOf("数据格式");
                 int index20 = -1;
                 if (selectedFields.Contains("图幅等高距")) index20 = dt.Columns.IndexOf("图幅等高距");
                 int index21 = -1;
                 if (selectedFields.Contains("图式及图号")) index21 = dt.Columns.IndexOf("图式及图号");
                 int index22 = -1;
                 if (selectedFields.Contains("数据采集方法及仪器")) index22 = dt.Columns.IndexOf("数据采集方法及仪器");

#else
                 int index9 = -1;
                 if (selectedFields.Contains("图幅接合表中西北图幅名称")) index9 = dt.Columns.IndexOf("图幅接合表中西北图幅名称");
                 int index10 = -1;
                 if (selectedFields.Contains("图幅接合表中北图幅名称")) index10 = dt.Columns.IndexOf("图幅接合表中北图幅名称");
                 int index11 = -1;
                 if (selectedFields.Contains("图幅接合表中东北图幅名称")) index11 = dt.Columns.IndexOf("图幅接合表中东北图幅名称");
                 int index12 = -1;
                 if (selectedFields.Contains("图幅接合表中西图幅名称")) index12 = dt.Columns.IndexOf("图幅接合表中西图幅名称");
                 int index13 = -1;
                 if (selectedFields.Contains("图幅接合表中东图幅名称")) index13 = dt.Columns.IndexOf("图幅接合表中东图幅名称");
                 int index14 = -1;
                 if (selectedFields.Contains("图幅接合表中西南图幅名称")) index14 = dt.Columns.IndexOf("图幅接合表中西南图幅名称");
                 int index15 = -1;
                 if (selectedFields.Contains("图幅接合表中南图幅名称")) index15 = dt.Columns.IndexOf("图幅接合表中南图幅名称");
                 int index16 = -1;
                 if (selectedFields.Contains("图幅接合表中东南图幅名称")) index16 = dt.Columns.IndexOf("图幅接合表中东南图幅名称");

                 
                 int index17 = -1;
                 if (selectedFields.Contains("图廓角点最小X坐标")) index17 = dt.Columns.IndexOf("图廓角点最小X坐标");
                 int index18 = -1;
                 if (selectedFields.Contains("图廓角点最小Y坐标")) index18 = dt.Columns.IndexOf("图廓角点最小Y坐标");
                 int index19 = -1;
                 if (selectedFields.Contains("图廓角点最大X坐标")) index19 = dt.Columns.IndexOf("图廓角点最大X坐标");
                 int index20 = -1;
                 if (selectedFields.Contains("图廓角点最大Y坐标")) index20 = dt.Columns.IndexOf("图廓角点最大Y坐标");
#endif





                 int failedCount = 0;
                foreach (DataRow pRow in dt.Rows)
                {
                    Application.DoEvents();
                    if (pRow["比例尺分母"] == DBNull.Value)
                    {
                        failedCount++;
                        continue;
                    }
                    string scale = pRow["比例尺分母"].ToString().Trim();
                    double dblScale;
                    if (!double.TryParse(scale, out dblScale))
                    {
                        failedCount++;
                        continue;
                    }
                    //if (dt.Columns.Contains("产品名称"))
                    //{
                    //    pRow["产品名称"] = cmbDataType.Text;
                    //}
                    object obj = pRow["图号"];
                    if (obj == DBNull.Value) continue;
                    string strMapNo = obj.ToString().Trim();
#if 市县基础地理信息系统
                       switch (scale)
                    {
                        case "500":
                            dblWidth = 250;
                            dblHeight = bln4X5 ? 200 : 250;
                            precision = 2;
                            break;
                        case "1000":
                            dblWidth = 500;
                            dblHeight = bln4X5 ? 400 : 500;
                            precision = 1;
                            break;
                        case "2000":
                            dblWidth = 1000;
                            dblHeight = bln4X5 ? 800 : 1000;
                            precision = 0;
                            break;
                        case "5000":
                            dblWidth = 2500;
                            dblHeight = bln4X5 ? 2000 : 2500;
                            precision = 1;
                            break;
                        case "10000":
                            dblWidth = 5000;
                            dblHeight = bln4X5 ? 4000 : 5000;
                            precision = 0;
                            break;
                        default:
                            {
                                continue;
                            }
                    }                                
                    float dblLeft, dblRight;
                    if (!MapNoUtility.CheckTfbh500(strMapNo, out dblLeft, out dblRight)) continue;
                    string [] strs= MapNoUtility.GetAdjacentTFBH(strMapNo, Convert.ToInt32(scale), blnYX, bln4X5);
                    if (index1 >= 0)
                    {
                        pRow[index1] = blnYX ? Math.Round(dblRight * 1000, 0) : Math.Round(dblLeft * 1000, 0);
                    }
                    if (index2 >= 0)
                    {
                        pRow[index2] = blnYX ? Math.Round(dblLeft * 1000, 0) : Math.Round(dblRight * 1000, 0);
                    }
                    if (index3 >= 0)
                    {
                        pRow[index3] = blnYX ? Math.Round(dblRight * 1000, 0) : Math.Round(dblLeft * 1000, 0);
                    }
                    if (index4 >= 0)
                    {
                        pRow[index4] = blnYX ? Math.Round(dblLeft * 1000 + dblHeight, 0) : Math.Round(dblRight * 1000 + dblHeight, 0);
                    }
                    if (index5 >= 0)
                    {
                        pRow[index5] = blnYX ? Math.Round(dblRight * 1000 + dblWidth, 0) : Math.Round(dblLeft * 1000 + dblWidth, 0);
                    }
                    if (index6 >= 0)
                    {
                        pRow[index6] = blnYX ? Math.Round(dblLeft * 1000 + dblHeight, 0) : Math.Round(dblRight * 1000 + dblHeight, 0);
                    }
                    if (index7 >= 0)
                    {
                        pRow[index7] = blnYX ? Math.Round(dblRight * 1000 + dblWidth, 0) : Math.Round(dblLeft * 1000 + dblWidth, 0);
                    }
                    if (index8 >= 0)
                    {
                        pRow[index8] = blnYX ? Math.Round(dblLeft * 1000, 0) : Math.Round(dblRight * 1000, 0);
                    }
                    if (index9 >= 0)
                    {
                        pRow[index9] = blnYX ?
                        ProcessMapNo( (dblLeft + dblHeight / 1000).ToString("F" + precision) + "-" + (dblRight - dblWidth / 1000).ToString("F" + precision) ):
                        ProcessMapNo( (dblLeft - dblWidth / 1000).ToString("F" + precision) + "-" + (dblRight + dblHeight / 1000).ToString("F" + precision));
                    }
                    if (index10 >= 0)
                    {
                        pRow[index10] = blnYX ?
                         ProcessMapNo((dblLeft + dblHeight / 1000).ToString("F" + precision) + "-" + (dblRight).ToString("F" + precision)) :
                         ProcessMapNo((dblLeft).ToString("F" + precision) + "-" + (dblRight + dblHeight / 1000).ToString("F" + precision));
                    }

                    if (index11 >= 0)
                    {
                        pRow[index11] = blnYX ?
                         ProcessMapNo((dblLeft + dblHeight / 1000).ToString("F" + precision) + "-" + (dblRight + dblWidth / 1000).ToString("F" + precision)) :
                         ProcessMapNo((dblLeft + dblWidth / 1000).ToString("F" + precision) + "-" + (dblRight + dblHeight / 1000).ToString("F" + precision));
                    }

                    if (index12 >= 0)
                    {
                        pRow[index12] = blnYX ?
                         ProcessMapNo((dblLeft).ToString("F" + precision) + "-" + (dblRight - dblWidth / 1000).ToString("F" + precision) ):
                         ProcessMapNo((dblLeft - dblWidth / 1000).ToString("F" + precision) + "-" + (dblRight).ToString("F" + precision));
                    }
                    if (index13 >= 0)
                    {
                        pRow[index13] = blnYX ?
                         ProcessMapNo((dblLeft).ToString("F" + precision) + "-" + (dblRight + dblWidth / 1000).ToString("F" + precision) ):
                         ProcessMapNo((dblLeft + dblWidth / 1000).ToString("F" + precision) + "-" + (dblRight).ToString("F" + precision));
                    }

                    if (index14 >= 0)
                    {
                        pRow[index14] = blnYX ?
                         ProcessMapNo((dblLeft - dblHeight / 1000).ToString("F" + precision) + "-" + (dblRight - dblWidth / 1000).ToString("F" + precision) ):
                         ProcessMapNo((dblLeft - dblWidth / 1000).ToString("F" + precision) + "-" + (dblRight - dblHeight / 1000).ToString("F" + precision));
                    }
                    if (index15 >= 0)
                    {
                        pRow[index15] = blnYX ?
                         ProcessMapNo((dblLeft - dblHeight / 1000).ToString("F" + precision) + "-" + (dblRight).ToString("F" + precision)) :
                         ProcessMapNo((dblLeft).ToString("F" + precision) + "-" + (dblRight - dblHeight / 1000).ToString("F" + precision));
                    }
                    if (index16 >= 0)
                    {
                        pRow[index16] = blnYX ?
                         ProcessMapNo((dblLeft - dblHeight / 1000).ToString("F" + precision) + "-" + (dblRight + dblWidth / 1000).ToString("F" + precision) ):
                         ProcessMapNo((dblLeft + dblWidth / 1000).ToString("F" + precision) + "-" + (dblRight - dblHeight / 1000).ToString("F" + precision));
                    }

                    if (index17 >= 0)
                    {
                        pRow[index17] = cmbDataType.Text;
                    }
                    if (index18 >= 0)
                    {
                        pRow[index18] = "秘密";
                    }
                    if (index19 >= 0)
                    {
                        if (cmbDataType.Text == "DLG")
                        {
                            pRow[index19] ="dwg";
                        }                                            
                    }
                    if (index20 >= 0)
                    {
                        pRow[index20] = 0.5;
                    }
                    if (index21 >= 0)
                    {
                        pRow[index21] = "1996年版图式";
                    }
                    if (index22 >= 0)
                    {
                        pRow[index22] ="解析法测图";
                    }


#else
                    double dblLong, dblLat;
                    double width =0;  //经差
                    double height = 0; //纬差
                    char rowNoMillion;
                    string strColNoMillion, strRowNo, strColNo;
                    switch (scale)
                    {
                        case "5000":
                            if (!MapNoUtility.CheckTfbh5000(strMapNo, out rowNoMillion, out strColNoMillion, out strRowNo, out strColNo, out dblLong, out dblLat)) continue;
                            width = 6.0 / 192;
                            height = 4.0 / 192;
                            break;
                        case "10000":
                            if (!MapNoUtility.CheckTfbh10000(strMapNo, out rowNoMillion, out strColNoMillion, out strRowNo, out strColNo, out dblLong, out dblLat)) continue;
                            width = 6.0/ 96;
                            height = 4.0 / 96;
                            break;
                        case "50000":
                            if (!MapNoUtility.CheckTfbh50000(strMapNo, out rowNoMillion, out strColNoMillion, out strRowNo, out strColNo, out dblLong, out dblLat)) continue;
                            width = 6.0 / 24;
                            height = 4.0 / 24;
                            break;
                        default:
                            continue;
                    }

                    double dblCenterLong= MetadataEditUtility.GetL0(dblLong);
                    double dblX1,dblY1,dblX2,dblY2,dblX3,dblY3,dblX4,dblY4;
                    MetadataEditUtility.BL2XY80(dblLat, dblLong, out dblX1, out dblY1, dblCenterLong);
                    MetadataEditUtility.BL2XY80(dblLat + height, dblLong, out dblX2, out dblY2, dblCenterLong);
                    MetadataEditUtility.BL2XY80(dblLat + height, dblLong + height, out dblX3, out dblY3, dblCenterLong);
                    MetadataEditUtility.BL2XY80(dblLat, dblLong + width, out dblX4, out dblY4, dblCenterLong); 

                    if (index1 >= 0)
                    {
                        pRow[index1] = dblX1;
                    }
                    if (index2 >= 0)
                    {
                        pRow[index2] = dblY1;
                    }
                    if (index3 >= 0)
                    {
                        pRow[index3] = dblX2;
                    }
                    if (index4 >= 0)
                    {
                        pRow[index4] = dblY2;
                    }
                    if (index5 >= 0)
                    {
                        pRow[index5] = dblX3;
                    }
                    if (index6 >= 0)
                    {
                        pRow[index6] = dblY3;
                    }
                    if (index7 >= 0)
                    {
                        pRow[index7] = dblX4;
                    }
                    if (index8 >= 0)
                    {
                        pRow[index8] = dblY4;
                    }


                    if (index9 >= 0)
                    {
                        pRow[index9] = MapNoUtility.GetWestNorthTfbh(strMapNo, "1:" + scale);                       
                    }
                    if (index10 >= 0)
                    {
                        pRow[index10] = MapNoUtility.GetNorthTfbh(strMapNo, "1:" + scale);                           
                    }
                    if (index11 >= 0)
                    {
                        pRow[index11] = MapNoUtility.GetEastNorthTfbh(strMapNo, "1:" + scale);          
                    }
                    if (index12 >= 0)
                    {
                        pRow[index12] = MapNoUtility.GetWestTfbh(strMapNo, "1:" + scale);          
                    }
                    if (index13 >= 0)
                    {
                        pRow[index13] = MapNoUtility.GetEastTfbh(strMapNo, "1:" + scale);          
                    }
                    if (index14 >= 0)
                    {
                        pRow[index14] = MapNoUtility.GetWestSouthTfbh(strMapNo, "1:" + scale);          
                    }
                    if (index15 >= 0)
                    {
                        pRow[index15] = MapNoUtility.GetSouthTfbh(strMapNo, "1:" + scale);          
                    }
                    if (index16 >= 0)
                    {
                        pRow[index16] = MapNoUtility.GetEastSouthTfbh(strMapNo, "1:" + scale);          
                    }

                    if (index17 >= 0)
                    {
                        pRow[index17] = dblLong;
                    }
                    if (index18 >= 0)
                    {
                        pRow[index18] = dblLat;
                    }
                   
                    if (index19 >= 0)
                    {
                        pRow[index19] = dblLong + width;
                    }
                    if (index20>= 0)
                    {
                        pRow[index20] = dblLat + height;
                    }
#endif

                  
                }
                 if (failedCount > 0)
                 {
                     MessageBox.Show("共有"+failedCount+"条记录更新失败,原因：比例尺分母为空或不正确！" , "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                 }
             }
             catch (System.Exception)
             {
             }
             finally
             {
                 this.Cursor = Cursors.Default;
             }
         }
         private void dataGridView1_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
         {
             string strColumn = dataGridView1.Columns[e.ColumnIndex].Name;
            
             for (int i = 0; i < cmbColumn.Items.Count; i++)
             {
                 if (cmbColumn.Items[i].ToString() == strColumn)
                 {
                     cmbColumn.SelectedIndex = i;

                     break;
                 }
             }
         }

         private void cmbTfSpec_SelectedIndexChanged(object sender, EventArgs e)
         {            
         }

         private void cmbTfNameStyle_SelectedIndexChanged(object sender, EventArgs e)
         {           
         }

         private void btnUpdateCells_Click(object sender, EventArgs e)
         {
             foreach (DataGridViewCell pCell in this.dataGridView1.SelectedCells)
             {
                 pCell.Value = txtCellValue.Text.Trim();
             }
         }

         private void cmbColumn_SelectedIndexChanged(object sender, EventArgs e)
         {
             txtCellValue.Text = "";
         }    
         private void btnAutoUpdate_Click(object sender, EventArgs e)
         {
             AutoCaculate();
         }

         private void dataGridView1_RowHeaderMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
         {
             try
             {
                 DataView dv = dataGridView1.DataSource as DataView;
                 DataTable dt = dv.Table;

                 DataGridViewRow pRow = dataGridView1.Rows[e.RowIndex];

                 FrmDetail frmDetail = new FrmDetail(dt, pRow);

                 frmDetail.ShowDialog();
             }
             catch (Exception ex)
             {
                 MessageBox.Show("修改详细信息出错：" + ex.Message, "出错", MessageBoxButtons.OK, MessageBoxIcon.Error);
             }
         }

         private void btnImport_Click(object sender, EventArgs e)
         {
             if (dataGridView1.DataSource == null) return;
             openFileDialog4.Filter = "xml文件(*.xml)|*.xml";
             openFileDialog4.Multiselect = true;
             if (openFileDialog4.ShowDialog() != DialogResult.OK) return;
             foreach (string strFile in openFileDialog4.FileNames)
             {
                 Xml2Row(strFile);
             }
         }
      
         private void dataGridView1_CellParsing(object sender, DataGridViewCellParsingEventArgs e)
         {
             
             DataView dv = dataGridView1.DataSource as DataView;
             DataTable dt = dv.Table;
             if (dt == null) return;        
             if (e.Value == null) return;
             string strValue = e.Value.ToString();
             Type t = dt.Columns[e.ColumnIndex].DataType;
             switch (t.Name)
             {
                 case "Single":
                 case "Double":
                 case "Decimal":
                 case "Int16":
                 case "Int32":
                 case "Int64":
                     {
                         double dbl;
                         if (!double.TryParse(strValue, out dbl))
                         {
                             MessageBox.Show("请输入数字！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                             dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = null;
                             return;
                         }
                         break;
                     }
                 case "DateTime":
                     {
                         DateTime date;
                         if (!DateTime.TryParse(strValue, out date))
                         {
                             MessageBox.Show("请输入日期！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                             dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = null;
                             return;
                         }
                         break;
                     }
                 default:
                     {
                         break;
                     }
             }
         }

         private void dataGridView1_DragDrop(object sender, DragEventArgs e)
         {
             if (e.Data.GetDataPresent(DataFormats.FileDrop))
             {
                 if (dataGridView1.DataSource == null) return;
                 DataView pDv = dataGridView1.DataSource as DataView;
                 int index = 0;
                 int count = dataGridView1.Rows.Count;

#if 市县基础地理信息系统
                  float dblLeft, dblRight;
                 double dblUnit = 1;
                 switch (cmbDataUnit.Text)
                 {
                     case "千米":
                         {
                             dblUnit = 1;
                             break;
                         }
                     case "百米":
                         {
                             dblUnit = 0.1;
                             break;
                         }
                     case "十米":
                         {
                             dblUnit = 0.01;
                             break;
                         }
                     case "米":
                         {
                             dblUnit = 0.001;
                             break;
                         }
                     default:
                         {
                             break;
                         }
                 }
#else
                 double dblLong, dblLat;
                 char rowNoMillion;
                 string strColNoMillion, strRowNo, strColNo;
#endif

                 string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
                 try
                 {
                     foreach (string str in files)
                     {
                         string strExtension = System.IO.Path.GetExtension(str).ToLower();
                         string strFileName = System.IO.Path.GetFileNameWithoutExtension(str).Trim();
                         switch (cmbDataType.Text)
                         {
                             case "DLG":
                                 if (!(strExtension == ".dwg" || strExtension == ".dgn")) continue;
                               
                                 break;
                             case "DEM":
                                 if (!(strExtension == ".tif" || strExtension == ".img" ))continue;                              
                                 break;
                             case "DOM":
                                 if (!(strExtension == ".tif" || strExtension == ".img")) continue;                               
                                 break;
                             case "DRG":
                                 if (!(strExtension == ".jpg" || strExtension == ".jpeg" || strExtension == ".bmp")) continue;                                
                                 break;
                             default:
                                 {
                                     continue ;
                                 }
                         }
                         string strTFBH_new = "";

                         int countLeft = 2;//小数点左侧最少位数，少于这个数补“0”
                         string strLeft = "", strRight = ""; ;

                          #if 市县基础地理信息系统
                          if (MapNoUtility.CheckTfbh500(strFileName, out dblLeft, out dblRight))
                          {
                              switch (cmbScale.Text)
                              {
                                  case "500":
                                      strTFBH_new = (dblLeft * dblUnit).ToString("F2") + "-" + (dblRight * dblUnit).ToString("F2");
                                      break;
                                  case "1000":
                                      strTFBH_new = (dblLeft * dblUnit).ToString("F1") + "-" + (dblRight * dblUnit).ToString("F1");
                                      break;
                                  case "2000":
                                      strTFBH_new = (dblLeft * dblUnit).ToString("F0") + "-" + (dblRight * dblUnit).ToString("F0");
                                      break;
                                  case "5000":
                                      strTFBH_new = (dblLeft * dblUnit).ToString("F1") + "-" + (dblRight * dblUnit).ToString("F1");
                                      break;
                                  case "10000":
                                      strTFBH_new = (dblLeft * dblUnit).ToString("F0") + "-" + (dblRight * dblUnit).ToString("F0");
                                      break;
                                  default:
                                      strTFBH_new = "";
                                      break;

                                
                              }
                          }
                          strTFBH_new= ProcessMapNo(strTFBH_new);
                          #else
                         switch (cmbScale.Text)
                         {
                             case "5000":
                                 if (!MapNoUtility.CheckTfbh5000(strFileName, out rowNoMillion, out strColNoMillion, out strRowNo, out strColNo, out dblLong, out dblLat)) continue;
                                 strTFBH_new = strFileName.ToUpper();
                                 break;
                             case "10000":
                                 if (!MapNoUtility.CheckTfbh10000(strFileName, out rowNoMillion, out strColNoMillion, out strRowNo, out strColNo, out dblLong, out dblLat)) continue;
                                 strTFBH_new = strFileName.ToUpper();
                                 break;
                             case "50000":
                                 if (!MapNoUtility.CheckTfbh50000(strFileName, out rowNoMillion, out strColNoMillion, out strRowNo, out strColNo, out dblLong, out dblLat)) continue;
                                 strTFBH_new = strFileName.ToUpper();
                                 break;
                             default:
                                 break;
                         }
                          #endif

                        
                         if (strTFBH_new == "") continue;
                         DataRow pRow = pDv.Table.NewRow();
                         pRow["图号"] = strTFBH_new;
                         pRow["比例尺分母"] = cmbScale.Text;
                         pDv.Table.Rows.Add(pRow);
                         index++;
                         dataGridView1.Rows[ index - 1].Tag = strFileName;
                     }
                 }
                 catch (Exception ex)
                 {
                 }
               
             }
         }

         private void dataGridView1_DragEnter(object sender, DragEventArgs e)
         {
             e.Effect = DragDropEffects.Copy;
         }

         private void button2_Click(object sender, EventArgs e)
         {
             FrmFileList frm = new FrmFileList();
             frm.ShowDialog(this);
         }


         /// <summary>
         /// 对图好处理:小数点左侧最少位数2，少于这个数补“0”
         /// </summary>
         public static string ProcessMapNo(string strMapNo)
         {
             string strMapNoNew = "";
             bool blnLeft = strMapNo.StartsWith("-");
             if (blnLeft) strMapNoNew = strMapNo.Remove(0, 1);
             else strMapNoNew = strMapNo;
             int index = strMapNoNew.IndexOf("-");
             if (index <= 0) return strMapNo;
             string left, right;
             //  left = blnLeft ? "-" + strMapNoNew.Substring(0, index) : strMapNoNew.Substring(0, index);
             left = strMapNoNew.Substring(0, index);
             right = strMapNoNew.Substring(index + 1);

             bool blnRight = right.StartsWith("-");
             if (blnRight) right = right.Remove(0, 1);

             if (left.Contains("."))
             {
                 string s1 = left.Substring(0, left.IndexOf("."));
                 string s2 = left.Substring(left.IndexOf(".") + 1);
                 if (s1.Length < 2)
                     s1 = s1.PadLeft(2, '0');
                 left = s1 + "." + s2;

             }
             if (right.Contains("."))
             {
                 string s1 = right.Substring(0, right.IndexOf("."));
                 string s2 = right.Substring(right.IndexOf(".") + 1);
                 if (s1.Length < 2)
                     s1 = s1.PadLeft(2, '0');
                 right = s1 + "." + s2;
             }
             if (blnLeft) left = "-" + left;
             if (blnRight) right = "-" + right;
             strMapNoNew = left + "-" + right;
             return strMapNoNew;
         }

         private void chkShowAllColumn_CheckedChanged(object sender, EventArgs e)
         {
             if (chkShowAllColumn.Checked)
             {
                 foreach (DataGridViewColumn col in dataGridView1.Columns)
                 {
                     if (col.Name.ToUpper() != "ID")
                         col.Visible = true;
                 }
             }
             else
             {
                 List<string> importCols = strImportCol.ToList();
                 foreach (DataGridViewColumn col in dataGridView1.Columns)
                 {

                     col.Visible = importCols.Contains(col.Name);
                 }
             }
         }


       
        
    }
}
